package com.chushouya.order.service.api.impl;

import com.alipay.api.domain.AlipayOpenMiniOrderCloseModel;
import com.chushouya.manager.service.common.AlipayClientCommonService;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.service.api.AlipayOpenMiniOrderCloseService;
import com.general.framework.core.exception.Ex;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class AlipayOpenMiniOrderCloseServiceImpl implements AlipayOpenMiniOrderCloseService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;

    @Resource
    private AlipayClientCommonService alipayClientCommonService;

    /**
     * 获取订单信息
     * @param orderId
     */
    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw new RuntimeException("订单不存在");
        }
        return orderEntity;
    }

    /**
     * 订单额外信息
     * @param orderId
     */
    private OrderExtendEntity getOrderExtend(Long orderId) {
        OrderExtendEntity orderExtendEntity = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtendEntity)) {
            throw Ex.business("订单扩展信息不存在");
        }
        return orderExtendEntity;
    }

    /**
     * 关闭订单
     * @param orderId
     */

    @Override
    public void orderClose(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        if (Strings.isEmpty(orderEntity.getOrderCenterNo())) {
            throw Ex.business("订单没有支付宝订单号，无法操作 订单号：{}", orderEntity.getOrderNo());
        }
        OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        AlipayOpenMiniOrderCloseModel alipayOpenMiniOrderCloseModel = new AlipayOpenMiniOrderCloseModel();
        alipayOpenMiniOrderCloseModel.setOutOrderId(orderEntity.getOrderNo());
        alipayOpenMiniOrderCloseModel.setOrderId(orderEntity.getOrderCenterNo());
        alipayOpenMiniOrderCloseModel.setUserId(orderExtendEntity.getOpenId());
        alipayOpenMiniOrderCloseModel.setReasonCode("3100");
//        alipayOpenMiniOrderCloseModel.setReason(orderEntity.getLastRemark());
        try {
            alipayClientCommonService.alipayOpenMiniOrderClose(alipayOpenMiniOrderCloseModel);
        } catch (Exception e) {
            throw Ex.business("订单关闭失败 {}", e.getMessage());
        }
    }

}
